const app = getApp();
const api = require('../../utils/api.js');
const util = require('../../utils/util.js');
const foot = require('../../templates/foot/index.js');
var cityData = require('../../utils/area.js');
var loginStatus = wx.getStorageSync("loginStatus");
const {
  $Toast
} = require('../../components/base/base');
var tabBar = foot.tabBar;
var tabBarList = [];

Page({

  data: {
    navBg: app.globalData.navBg,
    navColor: app.globalData.navColor,
    windowHeight: app.globalData.windowHeight - app.globalData.navHeight,
    navTop: app.globalData.navHeight,
    back: false,
    navBox: false,
    tabBar: [],
    logo: 'https://chattest.metromall.cn/wfm/images/logo.png',
    notice: '这里是第一条网站公告标题，点我看详情。这里是第二条网站公告标题，点我看详情。这里是第三条网站公告标题，点我看详情。',
    store: '',
    qyopen: false, //点击门店区域筛选滑动弹窗显示效果，默认不显示
    qyshow: true, //用户点击闭关区域的弹窗设置，默认不显示
    isfull: false,
    // cityleft: cityData.getCity(), //获取门店区域的下拉框筛选项内容
    citycenter: {}, //选择门店区域左边筛选框后的显示的中间内容部分
    cityright: {}, //选择门店区域的中间内容部分后显示的右边内容
    select1: '', //门店区域选中后的第二个子菜单，默认显示门店下的子菜单
    select2: '', //门店区域选择部分的中间
    select3: '', //门店区域选择部分的右边
    shownavindex: '',
    isScroll: true,
    carouselList: [],
    itemdetail: [],
    scrollHeight: app.globalData.windowHeight - app.globalData.navHeight - 100,
    goTop: true,
    showSkeleton: true
  },

  changeFood: function () {
    util.navigateTo('../commoditypool/commoditypool')
  },

  //设置初始门店信息
  setcity: function () {
    var that = this;
    that.setData({
      // select1: '上海',
      // citycenter: that.data.cityleft['上海'],
      store: '上海普陀商场'
    })
  },

  // 门店区域列表下拉框是否隐藏
  listqy: function (e) {
    if (this.data.qyopen) {
      this.setData({
        qyopen: false,
        qyshow: false,
        isfull: false,
        shownavindex: 0
      })
    } else {
      this.setData({
        qyopen: true,
        qyshow: false,
        isfull: true,
        shownavindex: e.currentTarget.dataset.nav
      })
    }

  },

  // 门店区域第一栏选择内容
  selectleft: function (e) {
    var that = this;
    wx.request({
      url: util.api + api.GetProvince,
      data: {
        BUSINESS_PARAMETERS: {},
        SYSTEM_PARAMETERS: {
          APP_ID: "M_P_G001",
          METHOD_ID: 0,
          ACCESS_TOKEN: "1w2Re3bE^og38",
          TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
          SIGN: "string"
        }
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        if (res.data.MESSAGE.MESSAGE_CODE == 1) {
          that.setData({
            cityleft: res.data.RESULT
          })
          console.log(res.data.RESULT)
          try {
            if (that.data.current === e.target.dataset.id) {
              return false;
            } else {
              that.setData({
                current: e.target.dataset.id,
              })
            }
            console.log(e.currentTarget.dataset.id)
          } catch (error) {
            
          }
          
        }

      },
      fail: function (res) {}
    })  
    // this.setData({
    //   cityright: {},
    //   citycenter: this.data.cityleft[e.currentTarget.dataset.city],
    //   select1: e.target.dataset.city,
    //   select2: ''
    // });
    // console.log(e.currentTarget.dataset.city)
  },

  // 门店区域中间栏选择的内容
  selectcenter: function (e) {
    let leftarea = this.data.select1;
    let centerarea = this.data.select2;
    let rightarea = this.data.select3;
    if (leftarea === "" || leftarea === null || leftarea === undefined || leftarea.length === 0) {
      $Toast({
        content: "请选择省份",
        icon: 'prompt_fill',
        duration: 1
      })
    } else {
      this.setData({
        cityright: this.data.citycenter[e.currentTarget.dataset.city],
        select2: e.target.dataset.city,
        select3: ''
      });
    }

  },

  // 门店区域右边栏选择的内容
  selectright: function (e) {
    let leftarea = this.data.select1;
    let centerarea = this.data.select2;
    let rightarea = this.data.select3;
    if (leftarea === "" || leftarea === null || leftarea === undefined || leftarea.length === 0) {
      $Toast({
        content: "请选择省份",
        icon: 'prompt_fill',
        duration: 1
      })
    } else if (centerarea === "" || centerarea === null || centerarea === undefined || centerarea.length === 0) {
      $Toast({
        content: "请选择市区",
        icon: 'prompt_fill',
        duration: 1
      })
      return;
    } else {
      this.setData({
        select3: e.currentTarget.dataset.city
      });
    }

  },

  // 点击灰色背景隐藏所有的筛选内容
  hidebg: function (e) {

    this.setData({
      qyopen: false,
      qyshow: true,
      isfull: false,
      shownavindex: 0,
    })

  },

  // 门店区域清空筛选项
  quyuEmpty: function () {
    this.setData({
      select1: '',
      select2: '',
      select3: ''
    })
  },

  // 门店区域选择筛选项后，点击提交
  submitFilter: function () {
    let leftarea = this.data.select1;
    let centerarea = this.data.select2;
    let rightarea = this.data.select3;

    if (leftarea === "" || leftarea === null || leftarea === undefined || leftarea.length === 0) {
      $Toast({
        content: "请选择省份",
        icon: 'prompt_fill',
        duration: 1
      })
      return;
    } else if (centerarea === "" || centerarea === null || centerarea === undefined || centerarea.length === 0) {
      $Toast({
        content: "请选择市区",
        icon: 'prompt_fill',
        duration: 1
      })
      return;
    } else if (rightarea === "" || rightarea === null || rightarea === undefined || rightarea.length === 0) {
      $Toast({
        content: "请选择商场",
        icon: 'prompt_fill',
        duration: 1
      })
      return;
    } else {
      this.setData({
        qyopen: false,
        qyshow: false,
        isfull: false,
        store: this.data.select3,
        shownavindex: 0
      })
      return;
    }

  },

  search: function () {
    util.navigateTo('../search/search')
    // wx.navigateTo({
    //   url: '../search/search'
    // })
  },

  //轮播图加载
  getAdFlashPicList: function () {
    var that = this;
    wx.request({
      url: util.api + api.GetAdFlashPicList,
      data: {
        BUSINESS_PARAMETERS: {
          userToekn: loginStatus.token,
          mcid: 2
        },
        SYSTEM_PARAMETERS: {
          APP_ID: "M_P_G001",
          METHOD_ID: 0,
          ACCESS_TOKEN: "1w2Re3bE^og38",
          TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
          SIGN: "string"
        }
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        if (res.data.MESSAGE.MESSAGE_CODE == 1) {
          that.setData({
            carouselList: res.data.RESULT
          })
        }

      },
      fail: function (res) {}
    })
  },

  //图片高度自适应
  imgH: function (e) {
    var winWid = wx.getSystemInfoSync().windowWidth; //获取当前屏幕的宽度
    var imgh = e.detail.height;　　　　　　　　　　　 //图片高度
    var imgw = e.detail.width;
    //等比设置swiper的高度 (即屏宽/swiper高度)=图片宽/图片高==》swiper高度=屏宽*图片高度/图片宽度
    var swiperH = winWid * imgh / imgw + "px"
    this.setData({
      imgHeight: swiperH　　　　　　　　 //设置高度
    })
  },

  //页面加载时购物车数量
  countCart: function (e) {
    var that = this;
    wx.request({
      url: util.api + api.GetShopcart,
      data: {
        BUSINESS_PARAMETERS: {
          userToekn: loginStatus.token,
          PostStaId: 22
        },
        SYSTEM_PARAMETERS: {
          APP_ID: "M_P_G001",
          METHOD_ID: 0,
          ACCESS_TOKEN: "1w2Re3bE^og38",
          TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
          SIGN: "string"
        }
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        if (res.data.MESSAGE.MESSAGE_CODE == 1) {
          var arr = res.data.RESULT || [];
          var counts = 0;
          //遍历购物车对其进行求和
          for (var i = 0; i < arr.length; i++) {
            counts = parseInt(counts) + parseInt(arr[i].Num);
          }
          let navCont = that.data.navCont;
          //购物车商品数量
          that.setData({
            navCont: counts
          })
        }

      },
      fail: function (res) {}
    })
  },

  //加入购物车实时数量
  cartNumber: function () {
    var that = this;
    wx.request({
      url: util.api + api.GetShopcart,
      data: {
        BUSINESS_PARAMETERS: {
          userToekn: loginStatus.token,
          PostStaId: 22
        },
        SYSTEM_PARAMETERS: {
          APP_ID: "M_P_G001",
          METHOD_ID: 0,
          ACCESS_TOKEN: "1w2Re3bE^og38",
          TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
          SIGN: "string"
        }
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        if (res.data.MESSAGE.MESSAGE_CODE == 1) {
          var arr = res.data.RESULT || [];
          var counts = 1;
          //遍历购物车对其进行求和
          for (var i = 0; i < arr.length; i++) {
            counts = parseInt(counts) + parseInt(arr[i].Num);
          }
          let navCont = that.data.navCont;
          //购物车商品数量
          that.setData({
            navCont: counts
          })
        }

      },
      fail: function (res) {}
    })
  },

  scroll: function (e) {
    var that = this;
    var listIndex = (e.detail.scrollTop + this.data.screenHeight) / (this.data.screenWidth * 0.4)
    if (e.detail.scrollTop > app.globalData.navHeight + 40) {
      this.setData({
        goTop: false
      });
      this.setData({
        listIndex: listIndex
      })
    } else {
      this.setData({
        goTop: true
      });
    }

  },

  //返回顶部
  goScrolltop: function (e) {
    var that = this;
    var top = that.data.scrollTop;
    if (top == 1) {
      top = 0;
    } else {
      top = 1;
    }

    that.setData({
      scrollTop: top
    })

  },

  // 栏目列表
  GetRecomProKindAPro: function () {
    var that = this;
    wx.request({
      url: util.api + api.GetRecomProKindAPro,
      data: {
        BUSINESS_PARAMETERS: {
          userToekn: loginStatus.token,
          PostStaId: 22
        },
        SYSTEM_PARAMETERS: {
          APP_ID: "M_P_G001",
          METHOD_ID: 0,
          ACCESS_TOKEN: "1w2Re3bE^og38",
          TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
          SIGN: "string"
        }
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        that.setData({
          GetRecomProKindAPro: res.data.RESULT
        })
        that.setData({
          showSkeleton: false
        })
        
        console.log(res.data.RESULT)
      },
      fail: function (res) {
        that.setData({
          showSkeleton: true
        })
      }

    })
  },

  // 加入购物车
  addCart: function (e) {
    var that = this;
    var pid = e.currentTarget.dataset.id;
    var id = [];
    id.push(pid)
    that.cartNumber();
    
    wx.request({
      url: util.api + api.AddOrModCart,
      data: {
        BUSINESS_PARAMETERS: {
          userToekn: loginStatus.token,
          PostStaId: 22,
          ProductIDs: id,
          nums: [1],
          plus: true
        },
        SYSTEM_PARAMETERS: {
          APP_ID: "M_P_G001",
          METHOD_ID: 0,
          ACCESS_TOKEN: "1w2Re3bE^og38",
          TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
          SIGN: "string"
        }
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        $Toast({
          content: "加入购物车成功!",
          icon: 'success',
          duration: 1
        });
      },
      fail: function (res) {}

    })

  },

  // 加入收藏夹
  collectionTap: function (e) {
    var that = this;
    var pid = e.currentTarget.dataset.id;
    var memCardIDs = e.currentTarget.dataset.memCardIDs;
    var ProKind = that.data.GetRecomProKindAPro;
    var id = [];
    id.push(pid)
    wx.request({
      url: util.api + api.ShoucangAdd,
      data: {
        BUSINESS_PARAMETERS: {
          userToekn: loginStatus.token,
          PostStaId: 22,
          ProductIDs: id,
          nums: [1],
          plus: true
        },
        SYSTEM_PARAMETERS: {
          APP_ID: "M_P_G001",
          METHOD_ID: 0,
          ACCESS_TOKEN: "1w2Re3bE^og38",
          TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
          SIGN: "string"
        }
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        $Toast({
          content: "加入收藏夹成功!",
          icon: 'success',
          duration: 1
        });
        
      },
      fail: function (res) {}

    })
    
  },

  gotoDetail: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var navcataid = that.data.navcataid;
    util.navigateTo('../productdetail/productdetail?id=' + id + '&navcataid=' + navcataid)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setcity();
    that.getAdFlashPicList();
    that.GetRecomProKindAPro();
    that.selectleft();
    //获取屏幕尺寸
    const screenWidth = wx.getSystemInfoSync().windowWidth;
    const screenHeight = wx.getSystemInfoSync().windowHeight;
    this.setData({
      listIndex: screenHeight / (screenWidth * 0.4),
      screenWidth: screenWidth,
      screenHeight: screenHeight
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {


  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.countCart();
    for (let i = 0; i < tabBar.length; i++) {
      tabBar[0].style = 1;
      tabBar[1].style = 0;
      tabBar[2].style = 0;
      tabBar[3].style = 0;
      tabBar[4].style = 0;
      tabBar[3].ico = 1;
      tabBarList.push(tabBar[i])
    }
    that.setData({
      tabBar: tabBarList
    })
    tabBarList.length = 0;
  }


})